package system

import org.apache.commons.lang.builder.HashCodeBuilder

/**
 * 用户权限 关联表----执行 s2-quickstart base StaffMember Authority 自动生成 没有修改
 */
//@ToString(cache=true, includeNames=true, includePackage=false)
class StaffMemberAuthority implements Serializable {

	StaffMember staffMember
	Authority authority
	@Override
	boolean equals(other) {
		if (!(other instanceof StaffMemberAuthority)) {
			return false
		}

		other.staffMember?.id == staffMember?.id &&
			other.authority?.id == authority?.id
	}
	@Override
	int hashCode() {
		def builder = new HashCodeBuilder()
		if (staffMember) builder.append(staffMember.id)
		if (authority) builder.append(authority.id)
		builder.toHashCode()
	}

	static StaffMemberAuthority get(String userId, String authorityId) {
		find 'from StaffMemberAuthority where staffMember.id=:userId and authority.id=:authorityId',
			[userId: userId, authorityId: authorityId]
	}

	static StaffMemberAuthority create(StaffMember staffMember, Authority authority, boolean flush = false) {
        if(!StaffMemberAuthority.findByStaffMemberAndAuthority(staffMember,authority))
		 new StaffMemberAuthority(staffMember: staffMember, authority: authority).save(flush: flush, insert: true)
        else
        null
	}
    //2012-2-15 fang add        为用户批量添加权限
    static  createManyAuthoritys(StaffMember staffMember, Set<Authority> authoritys, boolean flush = false) {
		authoritys.each {
             // new StaffMemberAuthority(staffMember: staffMember, authority: it).save(flush: flush, insert: true)
            StaffMemberAuthority.create(staffMember as StaffMember,it as Authority,flush)
        }

	}
	static boolean remove(StaffMember staffMember, Authority authority, boolean flush = false) {
		StaffMemberAuthority instance = StaffMemberAuthority.findByStaffMemberAndAuthority(staffMember, authority)
		if (!instance) {
			return false
		}
		instance.delete(flush: flush)
        println("用户"+staffMember+"移除权限 "+authority+" 成功")

		true
	}

	static void removeAll(StaffMember staffMember, int flag=0) {      //0全部 1,只删除可展示的,2,只删除不可展示的
        if(flag==1){
            def list=Authority.findAllByShowToJm(true)
           executeUpdate 'DELETE FROM StaffMemberAuthority WHERE authority in (:list) and staffMember.id=:staffMember', [list:list,staffMember: staffMember.id]
			//移除相应的快捷导航
        }
        else if(flag==2){
            def list=Authority.findAllByShowToJm(false)
           executeUpdate 'DELETE FROM StaffMemberAuthority WHERE authority in (:list) and staffMember.id=:staffMember', [list:list,staffMember: staffMember.id]
        }
        else{
			executeUpdate 'DELETE FROM StaffMemberAuthority WHERE staffMember.id=:staffMember', [staffMember: staffMember.id]
		}


	}

	static void removeAll(Authority authority) {
		executeUpdate 'DELETE FROM StaffMemberAuthority WHERE authority=:authority', [authority: authority]
	}

	static mapping = {
		id composite: ['authority', 'staffMember']
		version false
	}
}
